package com.mmc.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mmc.common.result.Result;
import com.mmc.entity.Message;
import com.mmc.service.MessageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 消息控制器
 *
 * @author kunfe
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/api/messages")
@RequiredArgsConstructor
@SaCheckLogin
public class MessageController {

    private final MessageService messageService;

    /**
     * 分页查询消息
     */
    @GetMapping("/page")
    public Result<Page<Message>> getMessagePage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer type,
            @RequestParam(required = false) Integer status) {
        
        Long userId = StpUtil.getLoginIdAsLong();
        Page<Message> page = new Page<>(current, size);
        Page<Message> result = messageService.getMessagePage(page, userId, type, status);
        
        return Result.ok(result);
    }

    /**
     * 获取未读消息数量
     */
    @GetMapping("/unread-count")
    public Result<Long> getUnreadCount() {
        Long userId = StpUtil.getLoginIdAsLong();
        Long count = messageService.getUnreadCount(userId);
        return Result.ok(count);
    }

    /**
     * 获取最新消息
     */
    @GetMapping("/latest")
    public Result<List<Message>> getLatestMessages(@RequestParam(defaultValue = "5") Integer limit) {
        Long userId = StpUtil.getLoginIdAsLong();
        List<Message> messages = messageService.getLatestMessages(userId, limit);
        return Result.ok(messages);
    }

    /**
     * 发送消息
     */
    @PostMapping("/send")
    public Result<Void> sendMessage(@Valid @RequestBody SendMessageRequest request) {
        Message message = new Message();
        message.setType(request.getType());
        message.setTitle(request.getTitle());
        message.setContent(request.getContent());
        message.setReceiverId(request.getReceiverId());
        message.setPriority(request.getPriority());
        message.setTags(request.getTags());
        
        boolean success = messageService.sendMessage(message);
        return success ? Result.ok() : Result.fail("发送失败");
    }

    /**
     * 批量发送消息
     */
    @PostMapping("/batch-send")
    public Result<Void> batchSendMessage(@Valid @RequestBody BatchSendMessageRequest request) {
        boolean success = messageService.batchSendMessage(
                request.getReceiverIds(),
                request.getTitle(),
                request.getContent(),
                request.getType()
        );
        return success ? Result.ok() : Result.fail("批量发送失败");
    }

    /**
     * 标记消息为已读
     */
    @PutMapping("/{id}/read")
    public Result<Void> markAsRead(@PathVariable Long id) {
        Long userId = StpUtil.getLoginIdAsLong();
        boolean success = messageService.markAsRead(id, userId);
        return success ? Result.ok() : Result.fail("操作失败");
    }

    /**
     * 批量标记为已读
     */
    @PutMapping("/batch-read")
    public Result<Void> batchMarkAsRead(@Valid @RequestBody BatchOperationRequest request) {
        Long userId = StpUtil.getLoginIdAsLong();
        boolean success = messageService.batchMarkAsRead(request.getIds(), userId);
        return success ? Result.ok() : Result.fail("操作失败");
    }

    /**
     * 全部标记为已读
     */
    @PutMapping("/read-all")
    public Result<Void> markAllAsRead() {
        Long userId = StpUtil.getLoginIdAsLong();
        boolean success = messageService.markAllAsRead(userId);
        return success ? Result.ok() : Result.fail("操作失败");
    }

    /**
     * 删除消息
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteMessage(@PathVariable Long id) {
        Long userId = StpUtil.getLoginIdAsLong();
        boolean success = messageService.deleteMessage(id, userId);
        return success ? Result.ok() : Result.fail("删除失败");
    }

    /**
     * 批量删除消息
     */
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteMessage(@Valid @RequestBody BatchOperationRequest request) {
        Long userId = StpUtil.getLoginIdAsLong();
        boolean success = messageService.batchDeleteMessage(request.getIds(), userId);
        return success ? Result.ok() : Result.fail("删除失败");
    }

    /**
     * 系统广播消息（需要管理员权限）
     */
    @PostMapping("/broadcast")
    public Result<Void> broadcastMessage(@Valid @RequestBody BroadcastMessageRequest request) {
        // TODO: 添加权限检查
        boolean success = messageService.broadcastMessage(
                request.getTitle(),
                request.getContent(),
                request.getType()
        );
        return success ? Result.ok() : Result.fail("广播失败");
    }

    /**
     * 发送消息请求
     */
    @Data
    public static class SendMessageRequest {
        @NotNull(message = "消息类型不能为空")
        private Integer type;
        
        @NotBlank(message = "消息标题不能为空")
        private String title;
        
        @NotBlank(message = "消息内容不能为空")
        private String content;
        
        @NotNull(message = "接收者不能为空")
        private Long receiverId;
        
        private Integer priority = 2;
        private String tags;
    }

    /**
     * 批量发送消息请求
     */
    @Data
    public static class BatchSendMessageRequest {
        @NotNull(message = "消息类型不能为空")
        private Integer type;
        
        @NotBlank(message = "消息标题不能为空")
        private String title;
        
        @NotBlank(message = "消息内容不能为空")
        private String content;
        
        @NotEmpty(message = "接收者列表不能为空")
        private List<Long> receiverIds;
    }

    /**
     * 批量操作请求
     */
    @Data
    public static class BatchOperationRequest {
        @NotEmpty(message = "操作ID列表不能为空")
        private List<Long> ids;
    }

    /**
     * 广播消息请求
     */
    @Data
    public static class BroadcastMessageRequest {
        @NotNull(message = "消息类型不能为空")
        private Integer type;
        
        @NotBlank(message = "消息标题不能为空")
        private String title;
        
        @NotBlank(message = "消息内容不能为空")
        private String content;
    }
} 